package com.example.springbootstartermqttprovider.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootstartermqttprovider.config.MqttProviderConfig;
import com.example.springbootstartermqttprovider.myservice.domain.TBill;
import com.example.springbootstartermqttprovider.myservice.service.TBillService;
import com.example.springbootstartermqttprovider.oss.OSSUtils;
import com.example.springbootstartermqttprovider.utils.AuthorizationTokenCON;
import com.example.springbootstartermqttprovider.utils.HikCloudOAuthTokenExample;
import com.example.springbootstartermqttprovider.utils.OAuthTokenResponse;
import com.example.springbootstartermqttprovider.utils.ResTest;
import com.example.springbootstartermqttprovider.yinhang.FileDownloadDemo;
import com.example.springbootstartermqttprovider.yinhang.UniqueIdGenerator;
import com.example.springbootstartermqttprovider.yinhang.WJ12Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@RestController
public class SendController {
    @Autowired
    private MqttProviderConfig providerClient;

    @Autowired
    private TBillService tBillService;

    @RequestMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(int qos,boolean retained,String topic,String message){
        try {
            providerClient.publish(qos, retained, topic, message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

    @GetMapping("/info")
    public ResTest info(){
        ResTest resTest = new ResTest();
        try {
            OAuthTokenResponse accessToken = HikCloudOAuthTokenExample.getAccessToken();
            System.out.println("accessToken"+ cn.hutool.json.JSONUtil.toJsonStr(accessToken));
            AuthorizationTokenCON authorizationToken = HikCloudOAuthTokenExample.getAuthorizationToken(accessToken.getAccess_token());
            System.out.println("authorizationToken"+ cn.hutool.json.JSONUtil.toJsonStr(authorizationToken));
            resTest.setCode(200);
            resTest.setMessage("获取成功");
            resTest.setContent(authorizationToken.getData().getToken());
            return resTest;
        } catch (Exception e) {
            e.printStackTrace();
            return resTest;
        }
    }


    @RequestMapping("/getHui")
    public ResponseEntity<Resource> getHui(@RequestParam("no") String no) throws Exception{
        WJ12Req wj12Req=new WJ12Req();
        wj12Req.setAcctNo("77250078801000001798");
        wj12Req.setFileDownloadPar(no);
        wj12Req.setFileDownloadFlag(1);
//        wj12Req.setFileDownloadPar("1");
        //请求参数
        System.out.println("请求参数  =========="+ JSONUtil.toJsonStr(wj12Req));
        String body =new FileDownloadDemo().BodyBeanToXml(wj12Req,"gb18030");
        String head = new FileDownloadDemo().getHeadXmlByTranceId("WJ12", "2027726208");
        String sendJson =new FileDownloadDemo().getSendJson(head,body);
        //step2: �õ����ĺ�ƴ�ӱ��ģ����ͽ���
//        String send = "XXXXXX<?xml version=\"1.0\" encoding=\"gb2312\"?><packet><head>.......</head><body><signature>"+sign+"</signature></body></packet>";//ƴ�ӱ���
        String ty="F"+ UniqueIdGenerator.generateUniqueId()+".pdf";
        String result = FileDownloadDemo.sendFileByDownload(sendJson,ty);
        System.out.println("returnMsg  rcv from host is : " + new String(result));
        // 转换为字节数组


        File file = new File(System.getProperty("java.io.tmpdir") + "/" +ty);
        // 3. 检查文件是否存在且可读
        if (!file.exists() || !file.canRead()) {
            return ResponseEntity.notFound().build();
        }
        String  mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE; // 默认二进制流
        // 5. 包装文件资源
        Resource resource = new FileSystemResource(file);

        // 6. 构建响应
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(mimeType))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + file.getName() + "\"")
                .body(resource);
    }
    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public String uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            String uuid = IdUtil.randomUUID();
            String originalFilename = file.getOriginalFilename();
            String fileName = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
            OSSUtils.getRandomFileName(file.getInputStream(),fileName);
            return  "https://jqtms.oss-cn-beijing.aliyuncs.com/upload"+"/"+fileName;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    /**
     * 流程1 获取转账接口
     * @param
     * @return
     */
    @RequestMapping("/transferMoneyInfo")
    public void transferMoneyInfo(@RequestBody DY47REQ dy47)  throws Exception{
        String beginTime="20250528";
        String endTime="20250528";
        //设置默认属性
//        body8804.setBeginDate(beginTime);
//        body8804.setEndDate(endTime);
//        body8804.setAcctNo("77250078801000001798");
//        String body = new FileDownloadDemo().BodyBeanToXml(body8804, "gb18030");
//        String head = new FileDownloadDemo().getHeadXmlByTranceId("8804", "2027726208");
//        String sendJson = new FileDownloadDemo().getSendJson(head, body);
//        System.out.println("returnMsg  rcv from host is : " + new String(sendJson));
//        String result = new FileDownloadDemo().sendByHttp(sendJson);
//        //step3: 将返回报文中的signature密文进行验签，获取交易返回的body明文
//        Map returnBody = new FileDownloadDemo().getReturnBody(true, result);
//        System.out.println("the verify is: " + returnBody);
//        String plain = returnBody.get("plain").toString();
////        String strippedXmlString = plain.replaceFirst("<body>", "").replaceFirst("</body>", "");
//        TransfermoneyInfo transfermoney = new FileDownloadDemo().XmlToBean(plain, TransfermoneyInfo.class);
//        List<LoopResultList> lists = transfermoney.getLists();
//        System.out.println(lists.get(0).getList().get(0).getAcceptNo());
//        System.out.println(JSONUtil.toJsonStr(lists));

        //核心参数
        dy47.setAcctNo("77250078801000001798");
        dy47.setBeginDate(beginTime);
        dy47.setEndDate(endTime);

        //组装A666数据信息
        String body1 = new FileDownloadDemo().BodyBeanToXml(dy47, "gb18030");
        String head1 = new FileDownloadDemo().getHeadXmlByTranceId("DY47", "2027726208");
        String sendJson1 = new FileDownloadDemo().getSendJson(head1, body1);
        String result1 = new FileDownloadDemo().sendByHttp(sendJson1);
        //step3: 将返回报文中的signature密文进行验签，获取交易返回的body明文
        Map returnBody1 = new FileDownloadDemo().getReturnBody(true, result1);
        String plain1 = returnBody1.get("plain").toString();
        DY47Response transfermoney1 = new FileDownloadDemo().XmlToBean(plain1, DY47Response.class);
        System.out.println(transfermoney1.getLoopResult().get(0).getAcceptNo());

    }



    @GetMapping("/uploadPay")
    public String uploadPay(String packNo) throws Exception
    {
        DY47REQ dy47 =new DY47REQ();
        dy47.setSummary(packNo);
        try
        {
            //查询数据表
            LambdaQueryWrapper<TBill> yu=new LambdaQueryWrapper<>();
            yu.eq(TBill::getSettlementNo,dy47.getSummary());
            List<TBill> list = tBillService.list(yu);
            String payTime = list.get(0).getPayTime().substring(0,10).replace("-", "");
            System.out.println(payTime);
            String beginTime=payTime;
            String endTime=payTime;

            dy47.setAcctNo("77250078801000001798");
            dy47.setBeginDate(beginTime);
            dy47.setEndDate(endTime);

            //组装A666数据信息
            String body1 = new FileDownloadDemo().BodyBeanToXml(dy47, "gb18030");
            String head1 = new FileDownloadDemo().getHeadXmlByTranceId("DY47", "2027726208");
            String sendJson1 = new FileDownloadDemo().getSendJson(head1, body1);
            String result1 = new FileDownloadDemo().sendByHttp(sendJson1);
            //step3: 将返回报文中的signature密文进行验签，获取交易返回的body明文
            Map returnBody1 = new FileDownloadDemo().getReturnBody(true, result1);
            String plain1 = returnBody1.get("plain").toString();
            DY47Response transfermoney1 = new FileDownloadDemo().XmlToBean(plain1, DY47Response.class);
            System.out.println(transfermoney1.getLoopResult().get(0).getAcceptNo());

            String no =transfermoney1.getLoopResult().get(0).getAcceptNo();

            WJ12Req wj12Req=new WJ12Req();
            wj12Req.setAcctNo("77250078801000001798");
            wj12Req.setFileDownloadPar(no);
            wj12Req.setFileDownloadFlag(1);
//        wj12Req.setFileDownloadPar("1");
            //请求参数
            System.out.println("请求参数  =========="+ JSONUtil.toJsonStr(wj12Req));
            String body =new FileDownloadDemo().BodyBeanToXml(wj12Req,"gb18030");
            String head = new FileDownloadDemo().getHeadXmlByTranceId("WJ12", "2027726208");
            String sendJson =new FileDownloadDemo().getSendJson(head,body);
            //step2: �õ����ĺ�ƴ�ӱ��ģ����ͽ���
//        String send = "XXXXXX<?xml version=\"1.0\" encoding=\"gb2312\"?><packet><head>.......</head><body><signature>"+sign+"</signature></body></packet>";//ƴ�ӱ���
            String ty="F"+ UniqueIdGenerator.generateUniqueId()+".pdf";
            String result = FileDownloadDemo.sendFileByDownload(sendJson,ty);
            System.out.println("returnMsg  rcv from host is : " + new String(result));
            // 转换为字节数组
            File file = new File(System.getProperty("java.io.tmpdir") + "/" +ty);
            String fileName = ty;
            OSSUtils.getRandomFileNameNew(file,fileName);
            TBill uup=new TBill();
            uup.setId(list.get(0).getId());
            uup.setPayFileUrl("https://jqtms.oss-cn-beijing.aliyuncs.com/upload"+"/"+fileName);
            tBillService.updateById(uup);
            return "200";
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "500";
        }
    }

}